#include "myMqttClient.h"
#include <iostream>
#include <sstream>
#include <iomanip>

std::string printControlMessageRaw(const ControlMessage& msg) 
{
    std::ostringstream oss;
    oss << "ControlMessage {" << std::endl;
    
    // 打印缺陷类型列表（原始数值）
    oss << "  defectTypes: [";
    for (size_t i = 0; i < msg.defectTypes.size(); ++i) {
        oss << static_cast<int>(msg.defectTypes[i]);
        if (i < msg.defectTypes.size() - 1) oss << ", ";
    }
    oss << "]" << std::endl;
    
    // 打印槽位映射
    oss << "  slotMapping: [";
    for (size_t i = 0; i < msg.slotMapping.size(); ++i) {
        oss << msg.slotMapping[i];
        if (i < msg.slotMapping.size() - 1) oss << ", ";
    }
    oss << "]" << std::endl;
    
    // 打印控制动作（原始数值）
    oss << "  action: " << static_cast<int>(msg.action) << std::endl;
    
    // 打印产品信息
    oss << "  productInfo: {" << std::endl;
    oss << "    model: " << msg.productInfo.model << std::endl;
    oss << "    batch: " << msg.productInfo.batch << std::endl;
    oss << "    serial: " << msg.productInfo.serial << std::endl;
    oss << "  }" << std::endl;
    
    oss << "}";
    return oss.str();
}

MyMqttClient::MyMqttClient(const std::vector<std::string>& topics, const ProtocolHandler &handler, PCBDetectionContext* pcbCtx)
    : MqttClient(topics), pHandler(handler), pPcbCtx(pcbCtx) {}

void MyMqttClient::handleMessage(const std::string& topic, const std::string& payload) 
{
    // 自定义消息处理逻辑
    std::cout << "[自定义处理] 主题: " << topic << ", 内容: " << payload << std::endl;
    
    // 示例：根据主题进行不同处理
    if (topic == "pcb/control") {
        std::cout << "系统状态更新: " << payload << std::endl;
        ControlMessage controlMsg = this->pHandler.decodeControlMessage(payload);
        this->pPcbCtx->updateFromControlMessage(controlMsg);
       // std::cout << printControlMessageRaw(controlMsg) << std::endl;
    } else {
        std::cout<<"该主题没有处理方法"<< topic << std::endl;
    }
}
